<?php

namespace app\admin\controller\workteam;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;

use fast\Date;
use fast\Tree;
use think\Collection;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;
use think\Queue;


/**
 * 项目管理
 */
class Project extends Backend
{

    protected $noNeedRight = ['info', 'selectpage','tasklist','adminlist','fileslist','gantt','customer'];
	protected $searchFields = 'name,customer_name,contacts_name';
    protected $w_config;
    protected $unAction=['gantt'];//清除layout 的方法集合
    public function _initialize()
    {
        if (in_array($this->request->action(),$this->unAction)){
            $this->layout=false;
        }
        parent::_initialize();
        $this->model = new  \app\admin\model\workteam\Project();
        $this->w_config = get_addon_config('workteam');
        $this->view->assign("w_config", $this->w_config);
        $this->view->assign("levelList", $this->model->getLevelList());
    }

    /**
     * 查看列表
     */
    public function index()
    {
        $scene = model('\app\admin\model\workteam\Scene');
        $scene_list = $scene->where('types', 'project')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');

        if ($this->request->isAjax()) {
            $filter_w = $this->getFilterWhere($scene_list);
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage($filter_w);
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->fetchSql(false)
                ->count();
            //任务排序方法，如果是空,把重要的，将要过期的，未完成的任务排序在前面
            if ($sort==''){
                $this->model->orderRaw("field(status,'0','1','2','3') ,level desc,id desc");
            }else{
                $this->model->order($sort, $order);
            }

            $list = $this->model
                ->where($where)
                ->with(['padmin' => function ($q) {
                    $q->field('id,nickname');
                },'sadmin' => function ($q) {
                    $q->field('id,nickname');
                }])
				
                ->where($filter_w)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();

            foreach ($list as $row){
                $row->hidden(['price','expenses']);//隐藏敏感信息
            }

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig("statusList", $this->model->getStatusList());
        $this->assignconfig("levelList",  $this->model->getLevelList());
        $this->assignconfig("scene_list", $scene_list);
        $this->view->assign("scene_list", $scene_list);

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $customer_name=$this->request->post("row[customer_id]_text");
            if (!$params) $this->error(__("提交参数有误"));

            $params['order_time'] = $params['order_time'] ? strtotime($params['order_time']) : time();
            $params['start_time'] = $params['start_time'] ? strtotime($params['start_time']) : time();
            $params['end_time'] = $params['end_time'] ? strtotime($params['end_time']) : time();
            $params['test_time'] = $params['test_time'] ? strtotime($params['test_time']) : time();
            $params['customer_name']=isset($params['customer_name'])?$params['customer_name']:$customer_name;
            if (count($params['jobs'])>0){
                $params['jobs']=implode(',', $params['jobs']);
            }
            $params = array_merge($params, [
                'create_admin_id' => $this->auth->id,
                'status'=>0
            ]);
            $params = $this->preExcludeFields($params);

            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException(true)->validate($validate);

                $result = $this->model->allowField(true)->save($params);
                $project_id = $this->model->id;
                //添加任务
                $task_data = $this->request->post("task/a");
                if ($task_data) {

                    foreach ($task_data as $k => &$row) {
                        if (!$row['name']) continue;//加项目的时候任务可以不用加
                        $row['project_id'] = $project_id;
                        $row['start_time'] = $row['start_time'] ? strtotime($row['start_time']) : time();
                        $row['end_time'] = $row['end_time'] ? strtotime($row['end_time']) : time();
                        $row['status'] = 0;
                        $taskModel = new  \app\admin\model\workteam\Task();
                        $result = $taskModel->add($project_id, $row);
                        if (!$result) {
                            \exception($taskModel->getError() . __("第{$k}行"));
                        }
                    }
                }

                //如果存在附件
                if (isset($params['image'])&&$params['image']) {
                    $images = explode(",", $params['image']);
                    //获取附件名称集合
                    $attachments = \app\common\model\Attachment::where('url', 'in', $images)->column('filename', 'url');
                    $files_data = array();
                    foreach ($images as $key => $v) {
                        $files_data[$key]['url'] = $v;
                        $files_data[$key]['admin_id'] = $this->auth->id;
                        $files_data[$key]['project_id'] = $project_id;
                        $files_data[$key]['task_id'] = 0;
                        $files_data[$key]['create_time'] = time();
                        $files_data[$key]['filename'] = isset($attachments[$v]) ? $attachments[$v] : $v;
                    }
                    $this->model->files()->saveAll($files_data);
                }

                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }


        }
        $taskModel = new  \app\admin\model\workteam\Task();

        $groupList = collection(AuthGroup::select())->toArray();

        $auth = new \addons\workteam\library\Auth();
        $groupdata=$auth->getAllDepartmentsTreeArray($this->auth->id);

        //项目编号前缀处理
        $replace_data=['Y'=>date('Y'),'m'=>date('m'),'d'=>date('d'),'H'=>date("H"),'i'=>date("i"),'s'=>date("s"),'rand'=>rand(100000,999999)];
        $pprefix=isset($this->w_config['pprefix'])?__($this->w_config['pprefix'], $replace_data):'';

        
        $this->view->assign("pprefix", $pprefix);
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("levelList", $taskModel->getLevelList());
        $this->view->assign("groupdata", $groupdata);
        return $this->view->fetch();
    }

    /**
     * 修改
     * @param null $ids
     * @return mixed
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        //判断是否有权限修改
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edProjectAuth($row, $this->auth)) {
            $this->error(__('项目管理人员才有权限修改'));
        }
        if ($this->request->isPost()) {
            if ($row->status==3)
                $this->error(__("项目已经归档不能操作"));
            $params = $this->request->post("row/a");

            if ($params) {

                if (in_array($params['status'], [2, 3])) {
                    if (!isset($params['complete_time']) || $params['complete_time'] <= 0) {
                        $this->error(__("请输入完成时间"));
                    }
                    $params['complete_time'] = strtotime($params['complete_time']);
                    //完成和归档状态处理
                    if ($params['status']==2&&$row->status!=2){
                        if (!$row->complete($params['complete_time'])){
                            $this->error($row->getError());
                        }

                    }else if ($params['status']==3){
                        if (!$row->guidang()){
                            $this->error($row->getError());
                        }
                    }
                }

                $params['order_time'] = $params['order_time'] ? strtotime($params['order_time']) : time();
                $params['start_time'] = $params['start_time'] ? strtotime($params['start_time']) : time();
                $params['end_time'] = $params['end_time'] ? strtotime($params['end_time']) : time();
                $params['test_time'] = $params['test_time'] ? strtotime($params['test_time']) : time();
                if (count($params['jobs'])>0){
                    $params['jobs']=implode(',', $params['jobs']);
                }
				if (isset($params['complete_time']) && !$params['complete_time']) {
                    unset($params['complete_time']);
                }

                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $w_config = get_addon_config('workteam');
        $this->view->assign("w_config", $w_config);
        $this->view->assign("row", $row);
        $this->view->assign("statusList", $this->model->getStatusList());
        return $this->view->fetch();

    }

    /**
     * 项目详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //判断是否有权限
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->projectAuth($row, $this->auth)) {
            $this->error(__('无权查看'));
        }


        $dataEchart = $this->model->burnHoursEchart($row);

        $taskModel = new  \app\admin\model\workteam\Task();
		$logModel = new \app\admin\model\workteam\Log();
        $w_config = get_addon_config('workteam');
        $this->view->assign("w_config", $w_config);
        $this->view->assign("row", $row);
        $this->assignconfig("statusList", $this->model->getStatusList());
        $this->assignconfig("levelList", $taskModel->getLevelList());
        $this->view->assign("statusList", $this->model->getStatusList());
		$this->view->assign('typeList', $logModel->getTypeList());
        $this->view->assign("dataEchart", $dataEchart);
		$this->assignconfig('createTypeList', $logModel->getCreateTypeList());
        return $this->view->fetch();
    }

    /**
     * 任务列表
     */
    public function tasklist($project_id = null)
    {
        if (!$project_id) {
            $this->error("");
        }
        $row = $this->model->get($project_id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //判断是否有权限
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->projectAuth($row, $this->auth)) {
            $this->error(__('项目人员才有权限'));
        }

        $this->model = new  \app\admin\model\workteam\Task();
        $filter_w = ['project_id' => $project_id];
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            $this->request->request(['custom' => $filter_w]);
            return parent::selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $this->model
            ->where($where)
            ->where($filter_w)
            ->fetchSql(false)
            ->count();

        //任务排序方法，如果是id,把重要的，将要过期的，未完成的任务排序在前面
        if ($sort=='id'){
            $this->model->orderRaw("field(status,'0','1','2') ,level desc,id desc");
        }else{
            $this->model->order($sort, $order);
        }

        $list = $this->model
            ->where($where)
            ->with(['admin' => function ($q) {
                $q->field('id,nickname');
            },
                'project' => function ($q) {
                    $q->field('id,name');
                },
				'ptask' => function($q){
					$q->field('id,name');
				}])
            ->where($filter_w)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $result = array("total" => $total, "rows" => $list,
            "extend" => [
                'statusList' => $this->model->getStatusList(),
                "levelList" => $this->model->getLevelList()
            ]);
        return json($result);
    }

    /**
     * 成员列表
     */
    public function adminlist($project_id = null)
    {
        if (!$project_id) {
            $this->error("");
        }
        $project = $this->model->where('id', $project_id)->field('admin_ids,task_count,task_hours')->find();
        if (!$project) $this->error(__("项目不存在"));

        $admin_ids = $project['admin_ids'];

        $adminModel = new \app\admin\model\Admin();
        $taskModel = new \app\admin\model\workteam\Task();
        $adminlist = $adminModel->where('id', 'in', $admin_ids)->field('id,username,nickname')->select();

        foreach ($adminlist as &$row) {
            $row = $row->toArray();
            //查询该用户任务量 TODO 未优化效率
            $task = $taskModel->where('project_id', $project_id)->where('admin_id', $row['id'])
                ->field('COUNT(*) AS task_count, sum(get_hours) as task_hours')->find();

            $row['task_percentage'] = $project['task_count'] > 0 ? sprintf('%.2f', $task['task_count'] / $project['task_count'] * 100) : '0';
            $row['hours_percentage'] = $project['task_hours'] > 0 ? sprintf('%.2f', $task['task_hours'] / $project['task_hours'] * 100) : '0';
            //延误率
            $delay_count = 0;
            $delay_percentage = 0;
            if ($task['task_count'] > 0) {
                $delay_count = $taskModel->where('project_id', $project_id)->where('admin_id', $row['id'])->where(function ($query) {
                    $query->where('complete_time>`end_time`')->whereOr('`complete_time` IS NULL AND unix_timestamp(now())>end_time');
                })->where('status', 'in', [1, 0, 2])->fetchSql(false)->count();
                $delay_percentage = $delay_count == 0 ? 0 : sprintf('%.2f', ($delay_count / $task['task_count'] * 100));
            }
            $row['delay_percentage'] = $delay_percentage;
            $row['delay_count'] = $delay_count;
            $row = array_merge($row, $task->toArray());
        }

        $result = array("total" => count($adminlist), "rows" => $adminlist);
        return json($result);
    }

    /**
     * 获取项目信息【不需要权限的】
     * @internal
     */
    public function info($ids = null)
    {
        $row = $this->model->hidden(['price'])->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->success('', '', $row);
    }

    /**
     * 打印
     * @param null $ids
     */
    public function print($ids = null)
    {
        $w_config = get_addon_config('workteam');
        $row = $this->model->with(['tasks' => function ($q) {
            return $q->where('status', "<>", '-1')->where('pid', '0');
        }])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        $this->view->assign("w_config", $w_config);
        return $this->view->fetch();
    }

    /**
     * 批量操作
     * @param string $ids
     */
    public function multi($ids = "")
    {

        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 完成项目
     * @param null $ids
     */
    public function complete($ids = null)
    {

        if (!$ids)
            $this->error(__('项目不存在'));

        $row = $this->model->find($ids);
        if (!$row)
            $this->error(__('项目不存在'));
        //判断是否有权限修改
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edProjectAuth($row, $this->auth)) {
            $this->error(__('项目管理人员才有权限修改'));
        }
        if (!$row->complete()){
            $this->error($row->getError());
        }
        $this->success();
    }

    /**
     * 归档项目
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function guidang($ids = null){
        if (!$ids)
            $this->error(__('项目不存在'));

        $row = $this->model->find($ids);
        if (!$row)
            $this->error(__('项目不存在'));

        //判断是否有权限修改
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edProjectAuth($row, $this->auth)) {
            $this->error(__('项目管理人员才有权限修改'));
        }
        if (!$row->guidang()){
            $this->error($row->getError());
        }
        $this->success();
    }


    /**
     * 附件
     */
    public function fileslist($project_id = null)
    {
        if (!$project_id) {
            $this->error(__("项目不存在"));
        }

        //判断是否有权限查看
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->projectAuth($project_id, $this->auth)) {
            $this->error(__('项目管理人员才有权限查看'));
        }

        $this->model = new \app\admin\model\workteam\Files();

        if ($this->request->isAjax()) {
            $filter_w = [];
            $filter_w['project_id'] = $project_id;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {

                $this->request->request(['custom' => $filter_w]);
                return parent::selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($filter_w)
                ->order($sort, $order)->fetchSql(false)
                ->count();
            $list = $this->model
                ->where($where)
                ->with(['admin' => function ($q) {
                    $q->field('id,nickname');
                },
                'task' => function ($q) {
                    $q->field('id,name');
                } ])

                ->where($filter_w)
                ->order($sort, $order)
                ->limit($offset, $limit)->fetchSql(false)
                ->select();

            foreach ($list as $k => &$row) {
                $row['fullurl'] = cdnurl($row['url'], true);
                $row['imagetype'] = pathinfo($row['url'], PATHINFO_EXTENSION);
            }


            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 附件上传
     */
    public function filesadd($project_id = null)
    {
        $url = $this->request->param('url');
        if (!$url || !$project_id) $this->error(__("参数不完整"));
        $row = $this->model->find($project_id);
        if (!$row) $this->error(__("项目不存在"));
        //判断是否有权限
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edProjectAuth($row, $this->auth)) {
            $this->error(__('项目管理人员才有权限操作'));
        }
        //获取附件名称
       $attachment= \app\common\model\Attachment::where('url',$url)->find();

        $files_data = array();
        $files_data['url'] = $url;
        $files_data['admin_id'] = $this->auth->id;
        $files_data['project_id'] = $project_id;
        $files_data['task_id'] = 0;
        $files_data['create_time'] = time();
        $files_data['filename'] = isset($attachment['filename'])?$attachment['filename']:$url;
        $row->files()->save($files_data);
        $this->success();
    }


    /**
     * 删除附件
     * @param string $ids
     */
    public function filesdel($ids = "")
    {

        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");

        if ($ids) {
            $this->model = new \app\admin\model\workteam\Files();
            $info = $this->model->where('id', $ids)->find();
            if (!$info) $this->error(__("记录不存在"));

            //判断是否有权限
            $auth = new \addons\workteam\library\Auth();
            if (!$auth->edProjectAuth($info['project_id'], $this->auth)) {
                $this->error(__('项目管理人员才有权限操作'));
            }

            $count = 0;
            Db::startTrans();
            try {
                $info->delete();
                $count++;
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));

        parent::del();
    }

    /**
     * 处理过滤where条件
     * @return array
     */
    private function getFilterWhere($scene_list)
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        $filter['scene_id'] = isset($filter['scene_id']) ? $filter['scene_id'] : 5;
        if (isset($filter['scene_id'])) {

            if (!isset($scene_list[$filter['scene_id']])) {
                $this->error(__("您没有权限"));
            }
			 $admin_id = $this->auth->id;
            $auth=new  \addons\workteam\library\Auth();
            switch ($filter['scene_id']) {
                case 5:

                    //全部
                    $childrenAdminIds = $auth->childrenAdminIds($this->auth,true);
                   
                    $filter_w[] = function ($query) use ($admin_id, $childrenAdminIds) {
                        $query->whereOr('project_admin_id', 'in', $childrenAdminIds)->whereOr([Db::raw("FIND_IN_SET(" . $admin_id . ",admin_ids)")])->whereOr('sales_admin_id', 'in', $childrenAdminIds);
                    };
                    break;
                case 6:
                    //我的
               
                    $filter_w[] = function ($query) use ($admin_id) {
                        $query->whereOr('project_admin_id',$admin_id)->whereOr('sales_admin_id',$admin_id);
                    };
                    break;
                case 7:
                    //下属
                    $childrenAdminIds = $auth->childrenAdminIds($this->auth,false);
                    if ( $childrenAdminIds){
						 $filter_w[] = function ($query) use ($admin_id, $childrenAdminIds) {
							$query->whereOr('project_admin_id', 'in', $childrenAdminIds)->whereOr('sales_admin_id', 'in', $childrenAdminIds);
						};
                    }else{
                        $filter_w['project_admin_id'] = "-1";
                    }

                    break;
                case 8:
                    //参与
                    $admin_id = $this->auth->id;
                    $filter_w[] = function ($query) use ($admin_id) {
                        $query->where([Db::raw("FIND_IN_SET(" . $admin_id . ",admin_ids)")]);
                    };
                    break;
                default://其它的还做TODO
                    $filter_w['project_admin_id'] = $this->auth->id;
            }
            if (isset($filter['expire_type'])) {
                $this->expire_type = $filter['expire_type'];
                unset($filter['expire_type']);
            }
            unset($filter['scene_id']);
            $this->request->get(['filter' => json_encode($filter)]);
        }

		if($this->request->param('customer_id',0)){
			$filter_w['customer_id'] = $this->request->param('customer_id');
		}

        return $filter_w;
    }

    /**
     * 甘特图
     * @return string
     * @throws Exception
     */
    public function gantt($project_id = null){
        if (!$project_id) {
            $this->error("");
        }
        $prow = $this->model->get($project_id);

        if (!$prow) {
            $this->error(__('No Results were found'));
        }
        //判断是否有权限
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->projectAuth($prow, $this->auth)) {
            $this->error(__('项目人员才有权限操作'));
        }

        $this->model = new  \app\admin\model\workteam\Task();
        $filter_w = ['project_id' => $project_id];


        $lists = $this->model
            ->where($filter_w)->fetchSql(false)
            ->with(['admin' => function ($q) {
                $q->field('id,nickname');
            }])
            ->select();

        $tree=new  \addons\workteam\library\Gantt();


        $tree->init(collection($lists)->toArray());

        $lists=($tree->getLevelArray(0));

        $tasklist=array();
        $depends=array();
        foreach ($lists as $key=>$row){
            $depends[$row['id']]=$key;//用于依赖
            $temp=array();
            $temp['id']=$row['id'];
            $temp['name']=$row['name'];
            $temp['progress']=$row['progress'];
            $temp['code']=$row['id'];
            $temp['level']=$row['level'];
            //状态处理
            if ($row['status']==0){
                $temp['status']='STATUS_SUSPENDED';
            }elseif ($row['status']==2){
                $temp['status']='STATUS_DONE';
            }elseif ($row['status']==1){
                $temp['status']='STATUS_ACTIVE';
            }else{
                $temp['status']='STATUS_WAITING';
            }
            $temp['statusText']=$row['status_text'];
            $temp['admin']=$row['admin'];//负责人
            $duration=intval(Date::span($row['start_time'],$row['end_time'],'days'))+1;//获取时间差
            $temp['duration']=$duration==0?1:$duration;//至少是1天 不能有小数
            $temp['plan_hours']=floatval($row['plan_hours']);



            $temp['canWrite']=false;
            $temp['start']=strtotime(date('Y-m-d',$row['start_time']))*1000;
            $temp['end']=strtotime(date('Y-m-d',$row['end_time']))*1000;




            $tasklist[]=$temp;
        }

        $this->view->assign([
            'tasklist' => $tasklist,
            'row'=>$prow
        ]);

        return $this->view->fetch('');
    }

    /**
     * 添加项目动态
     * @param string $ids 项目ID
     */
    public function addlog($ids = ""){


        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        //判断是否有权限修改
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edProjectAuth($row, $this->auth)) {
            $this->error(__('项目管理人员才有权限操作'));
        }
        //如果项目归档了，就不给操作
        if ($row->status==3)
            $this->error(__("项目状态不正常"));



        $this->model = new  \app\admin\model\workteam\Log();
        $this->view->assign("typeList", $this->model->getTypeList());

        if ($this->request->isPost()){

            $params = $this->request->post("row/a");
            if (!$params) $this->error(__("提交参数有误"));

            if (!isset($params['title'])||!$params['title']){
                $this->error(__("请输入标题"));
            }
            if (!isset($params['content'])||!$params['content']){
                $this->error(__("请输入内容"));
            }

            if (isset($params['notice'])&&!$params['admin_ids']){
                $this->error(__("请选择通知人员"));
            }

            $result = false;
            Db::startTrans();
            try {
               $result= \app\admin\model\workteam\Log::record($ids, 0, $params['title'],$params['content'],isset($params['type'])?$params['type']:0,1, $params['service_client']);
               if ($result&&isset($params['notice'])){
                   //消息通知
				   $params['link'] = config('admin.crm_url').url('workteam/log/detail',['ids'=>$result->id]);
                   $params['key']='notice_project_log';
                   $params=array_merge($row->toArray(),$params);
                   Queue::push('addons\workteam\library\notice\queue\ProjectJob',$params);
               }

                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();




        }
        $this->view->assign([
            'row'=>$row
        ]);
		$facrm_config = get_addon_config('facrm');
		$this->view->assign("service_client", $facrm_config['service_client']);
        return $this->view->fetch();
    }

    /**
     * @internal
     */
    public function selectpage($filter_w = array())
    {
        if (!$filter_w) {
            $scene = model('\app\admin\model\workteam\Scene');
            $scene_list = $scene->where('types', 'project')
                ->where(function ($query) {
                    $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
                })
                ->column('id,name');
            $filter_w = $this->getFilterWhere($scene_list);
        }


        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($filter_w)->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)->where($filter_w)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);

    }

    /**
     * 删除
     * @param string $ids
     */
    public function del($ids = "")
    {
        if (!$ids)
            $this->error(__('项目不存在'));

        $row = $this->model->find($ids);
        if (!$row)
            $this->error(__('项目不存在'));

        //判断是否有权限
        $auth = new \addons\workteam\library\Auth();
        if (!$auth->edProjectAuth($row, $this->auth)) {
            $this->error(__('项目管理人员才有权限'));
        }
        if ($row->status!=-1) {
            //要关闭的项目才给删除，以防误操作
            $this->error(__('不是关闭状态的项目，不能删除！'));
        }

        Db::startTrans();
        try {
            //删除任务
            \app\admin\model\workteam\Task::where('project_id',$row->id)->delete();
            //删除日志动态
            \app\admin\model\workteam\Log::where('project_id',$row->id)->delete();
            //删除附件
            \app\admin\model\workteam\Files::where('project_id',$row->id)->delete();
            $row->delete();

            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();



    }

	public function customer($ids){

        $scene = model('\app\admin\model\workteam\Scene');
        $scene_list = $scene->where('types', 'project')
            ->where(function ($query) {
                $query->where('admin_id', 0)->whereor('admin_id', $this->auth->id);
            })
            ->column('id,name');

        $this->assignconfig("statusList", $this->model->getStatusList());
        $this->assignconfig("levelList",  $this->model->getLevelList());
        $this->assignconfig("scene_list", $scene_list);
        $this->view->assign("scene_list", $scene_list);
		$this->assignconfig("customer_id", $ids);

		return $this->view->fetch();
	}


}
